const { randPassword } = require("../../../utils/randomValues");// 获取随机口令方法
const { insertEnterIntoActivity, getEnterIntoActivity, updateEnterIntoActivity, updateActivityList } = require("../../../api/activity");// 调用方法对数据库操作
let that = null;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        cardCur: 0,// 滚动卡片初始值，判断当前滚动卡片是哪张
        activity: {},// 活动想去列表
        user: {},// 缓存里的用户信息
        is_admin: [],// 判断是否为活动管理员，is是动词，所以下划线
        is_show: true,// 判断显示工作人员还是获取口令，true：工作人员，false:获取口令
        is_start: true,// 判断活动是否开始，已开始为true
        is_end: false,// 判断活动是否已结束，已结束为true
        modalName: null,// 模态框名字
        luck_draw_is_end: false,// 判断抽奖是否结束,结束时显示
        prize_name: '',// 抽奖滚动的礼物名字
        prize_index: 0,// 抽奖礼品下标
        prizeList: [],// 用于显示我的礼物,
        exist_prizeList: false,// 用户是否有礼物, 存在为true
        currentPage: 0,// 页面数
        loadMore: false, //"上拉加载"的变量，默认false，隐藏  此处没有用到，只是复制黏贴信息
        loadAll: false, //“没有数据”的变量，默认false，隐藏  
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        that = this;
        let nowTime = new Date().getTime();
        let activity = JSON.parse(options.activity);
        if (activity._endTime < nowTime) {// 判断活动是否结束了
            that.setData({
                is_end: true,
                activity: activity,
            })
        } else if(activity._startTime > nowTime) {
            that.setData({
                is_start: false,
                activity: activity,
            })
        } else {
            let user = wx.getStorageSync('user');
            let is_admin = wx.getStorageSync('is_admin');
            if (is_admin != '') {// 判断是否存在is_admin这个缓存
                is_admin.forEach(admin => {// 循环存在的is_admin集合
                    if (admin._id == activity._id && admin.is_admin == 1) {// 判断是否为该活动的管理员
                        that.setData({
                            is_show: false,
                        })
                    }
                });
            }
            that.setData({
                user: user,
                is_admin: is_admin,
                activity: activity,
            })
        }
    },

    /*
    * 滑块滚动，滑块列表下标
    */
    cardSwiper(e) {
        this.setData({
            cardCur: e.detail.current
        })
    },

    /**
     * 显示我的奖品列表
     */
    async showMyPrize() {
        wx.showLoading({
            title: '数据获取中...',
        })
        await getEnterIntoActivity({ _openid: that.data.user._openid, prize_gain: true }, that.data.currentPage, that);
        wx.hideLoading({
            success: (res) => { },
        })
    },

    /**
     * 我的奖品列表上拉触底事件
     */
    async scrollReachBottom() {
        // 判断是否加载更多
        if (!that.data.loadMore && !that.data.loadAll) {
            console.log('上拉触底');
            that.setData({
                loadMore: true, //加载中  
                loadAll: false //是否加载完所有数据
            });
            await getEnterIntoActivity({ _openid: that.data.user._openid, prize_gain: true } ,that.data.currentPage, that);
        }
    },

    /**
     * 输入adminPassword
     */
    inputAdminPassword() {
        wx.showModal({
            title: '工作人员输入密码获取口令',
            editable: true,
            placeholderText: '请输入密码',
        }).then(res => {
            let editText = res.content;
            if (res.confirm) {// 是否按了确定按钮
                if (editText == '') {// 判断密码是否有输入
                    wx.showToast({
                        title: '密码不能为空',
                        icon: "none"
                    })
                } else if (editText != that.data.activity.admin_password) {// 判断密码输入是否正确
                    wx.showToast({
                        title: '密码不正确',
                        icon: "none"
                    })
                } else {// 输入密码正确
                    let is_admin = [];
                    if (that.data.is_admin == []) {// 判断缓存没有is_admin
                        is_admin = [{ _id: that.data.activity._id, is_admin: 1 }];
                    } else {// 缓存有is_admin，有别的活动的admin
                        is_admin = that.data.is_admin;
                        is_admin[is_admin.length] = { _id: that.data.activity._id, is_admin: 1 };
                    }
                    // 将数据添加到data和storage
                    wx.setStorageSync('is_admin', is_admin);
                    that.setData({
                        is_admin: [is_admin],
                        is_show: false,
                    })
                    that.getCommand();// 获取口令方法
                }
            } else if (res.cancel) {
                console.log('用户点击取消');
            }
        })
    },

    /**
     * 获取口令
     */
    async getCommand() {
        wx.showLoading({
            title: '获取口令中...',
            mask: true,
        })
        let command = randPassword(4);
        let insertCommandData = {
            activity_id: that.data.activity._id,
            activity_name: that.data.activity.title,
            command: command,
            _createTime: Date.now(),
            _updateTime: Date.now(),
        };
        let enterIntoActivity = await insertEnterIntoActivity(insertCommandData).then(res => { return res; });
        // 判断是否添加成功
        if (enterIntoActivity.result.errMsg == "collection.add:ok") {
            console.log('add complete!');
            wx.hideLoading({
                success: (res) => { },
            })
            wx.showModal({
                title: '随机口令',
                content: command,
                showCancel: false,
            })
        } else {
            console.log('add fail!');
            wx.hideLoading({
                success: (res) => { },
            })
            wx.showToast({
                title: '获取口令失败，请检查网络重新获取，多次不行通知管理员',
                icon: "none",
                duration: 2000,
            })
        }

    },

    /**
     * 点击抽奖按钮事件
     */
    async getPrize() {
        let is_enterIntoActivity = await getEnterIntoActivity({ activity_id: that.data.activity._id, _openid: that.data.user._openid }).then(res => { return res; });
        if (is_enterIntoActivity.length == 0) {// 判断用户是否参加了该活动了
            if (that.data.activity.type == 1) {// 判断是否口令抽奖
                wx.showModal({
                    title: '输入口令',
                    editable: true,
                    placeholderText: '请输入口令',
                }).then(async (res) => {
                    if (res.confirm) {// 判断是否为确定按钮
                        let enterIntoActivity = await getEnterIntoActivity({ activity_id: that.data.activity._id, command: res.content }).then(res => { return res; });
                        if (enterIntoActivity.length == 0) {// 判断口令是否存在
                            wx.showToast({
                                title: '输入的口令有误',
                                icon: 'none',
                                duration: 2000,
                            })
                        } else {
                            if (enterIntoActivity[0]._openid != undefined) {// 判断口令是否被使用了
                                wx.showToast({
                                    title: '该口令已被别人使用过了，请重新输入',
                                    icon: 'none',
                                    duration: 2000,
                                })
                            } else {
                                // 开始抽奖
                                await that.showModal({ command: res.content, activity_id: that.data.activity._id });
                            }
                        }
                    }
                });
            } else {
                //开始抽奖
                await that.showModal();
            }
        } else {
            wx.showToast({
                title: '你已经参加过这次活动了',
                icon: 'none',
                duration: 2000,
            })
        }


    },

    /**
     * 显示模态框
     */
    async showModal(whereData) {
        //显示模态框
        that.setData({
            modalName: 'Modal',
        })
        const prizeList = JSON.parse(JSON.stringify(that.data.activity.prizes));
        prizeList[prizeList.length] = { prize_name: "谢谢参与" };
        that.setData({
            prize_name: prizeList[0].prize_name,
        });
        await setTimeout(async () => {
            await that.startLuckDraw(prizeList, whereData);
        }, 500);
    },

    /**
     * 隐藏模态框
     */
    hideModal() {
        this.setData({
            modalName: null
        })
    },

    /**
     * 开始抽奖
     */
    async startLuckDraw(prizeList, whereData) {
        //开始抽奖，设置定时器
        let interval = setInterval(() => {
            let prize_index = that.data.prize_index;
            if (prize_index == prizeList.length) {// 判断循环期间所有奖品是否已全部展示，是的话重新循环
                prize_index = 0;
            }
            that.setData({
                prize_name: prizeList[prize_index].prize_name,
                prize_index: prize_index + 1,
            })
        }, 100);
        /**
         * 开始使用算法，通过随机数获取奖品
         */
        // var array = prizeList;// 获取数据库，获奖数组
        var sum = 0;// 设置不同区间，奖品A在0.01~0.10，奖品B在0.11~0.30，奖品C早0.31~0.90，没获奖0.90~1.00
        var random = Math.floor(Math.random() * 10000);//获取一个随机数，这是抽奖者的幸运数。
        var is_prize = false; // 判断是否能获奖，能则为true，否则为false；
        let setData = { activity_name: that.data.activity.title };
        for (let prize_index = 0; prize_index < prizeList.length - 1; prize_index++) {// 循环每个奖项，判断是否获得奖励
            sum = sum + (prizeList[prize_index].prize_num - prizeList[prize_index].prize_gain_num) * prizeList[prize_index].prize_chance * 100;
            console.log(random);
            console.log(sum);
            if (random < sum) {// 判断是否获得奖励，奖品A在0.01~0.10，奖品B在0.11~0.30，奖品C早0.31~0.90，没获奖0.90~1.00
                console.log("恭喜获奖，奖品为：" + prizeList[prize_index].prize_name);
                is_prize = true;
                setData.prize_gain = true;
                setData.prize_name = prizeList[prize_index].prize_name;
                setData.prize_logo = prizeList[prize_index].prize_logo;
                // 改变activity数据
                let activityPrizes = JSON.parse(JSON.stringify(that.data.activity.prizes));
                for (let index=0; index < activityPrizes.length; index++) {
                    if (activityPrizes[index].prize_name == setData.prize_name) {
                        let prize_gain_num = 'activity.prizes[' + index + '].prize_gain_num';
                        that.setData({
                            [prize_gain_num]: activityPrizes[index].prize_gain_num + 1,
                        });
                        activityPrizes[index].prize_gain_num = activityPrizes[index].prize_gain_num + 1;
                    }
                }

                let activityList = await updateActivityList({ _id: that.data.activity._id }, { prizes: activityPrizes, });
                // 判断是否修改成功
                if (activityList.result.errMsg == "collection.update:ok") {
                    console.log(activityList.result.errMsg);
                } else {
                    console.log(activityList.result.errMsg);
                    wx.showToast({
                        title: '抽奖失败，请联系工作人员',
                        icon: "none",
                        duration: 2000,
                    })
                }
                break;// 获奖需要跳出循环
            }
        }
        if (!is_prize) {// 判断是否没有获奖
            setData.prize_gain = false;
            setData.prize_name = "谢谢参与"
            console.log("sorry,你没获奖");
        }

        // 改变enter_into_activity数据
        if (that.data.activity.type == 1) {// 判断是否需要口令抽奖的，口令抽奖调用更新，非口令抽奖调用添加
            let enterIntoActivity = await updateEnterIntoActivity(whereData, setData);
            that.endLuckDraw(enterIntoActivity, "collection.update:ok", interval, setData);
        } else {
            setData._createTime = Date.now();
            setData.activity_id = that.data.activity._id;
            let enterIntoActivity = await insertEnterIntoActivity(setData);
            that.endLuckDraw(enterIntoActivity, "collection.add:ok", interval, setData);
        }
    },

    /**
     * 结束抽奖,取消定时器
     */
    endLuckDraw(enterIntoActivity, enterIntoActivityValue, interval, setData) {
        // 判断是否添加成功
        if (enterIntoActivity.result.errMsg == enterIntoActivityValue) {
            console.log(enterIntoActivity.result.errMsg);
            setTimeout(() => {
                clearInterval(interval);
                that.setData({
                    prize_name: setData.prize_name,
                    luck_draw_is_end: true,
                });
            }, 1500)
        } else {
            console.log(enterIntoActivity.result.errMsg);
            setTimeout(() => {
                clearInterval(interval);
                that.setData({
                    prize_name: setData.prize_name,
                    luck_draw_is_end: true,
                });
            }, 1500)
            wx.showToast({
                title: '抽奖失败，请联系工作人员',
                icon: "none",
                duration: 2000,
            })
        }
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: '首页',
            path: '/pages/CA/home/home',
            imageUrl: '../../../images/share.png'
        }
    },

})